package cn.wolfcode.MQ.listener;

import cn.wolfcode.mq.MQConstant;
import cn.wolfcode.mq.OrderMQResult;
import cn.wolfcode.service.WebSocketServer;
import com.alibaba.fastjson.JSON;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 普发忠
 * @Date: 2021/11/11/14:17
 */
@Component
@RocketMQMessageListener(
        topic = MQConstant.ORDER_RESULT_TOPIC,
        consumerGroup = "order_result_topic-consumer"
)
public class OrderResultistener implements RocketMQListener<OrderMQResult> {
    @Autowired
    private RocketMQTemplate rocketMQTemplate;

    @Override
    public void onMessage(OrderMQResult ret) {
// 从websocket获取 service对象 ret取出数据通过，传递给客户端
        //map必须先有数据
        WebSocketServer webSocketServer=null;
        int i=3;
        do {
            webSocketServer = WebSocketServer.clients.get(ret.getToken());
            if (webSocketServer == null) {
                try {
                    TimeUnit.SECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }finally {
                    i--;
                }
            }else{
                break;
            }
        }while (i>0);
        
        if (webSocketServer!=null){
            String msg= JSON.toJSONString(ret);
            try {
                webSocketServer.getSession().getBasicRemote().sendText(msg);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                try {
                    webSocketServer.getSession().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
}
